﻿Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Text
Imports System.Windows.Forms
Imports System.Xml
Imports System.IO
Imports System.Net.Sockets
'--
Imports CrystalDecisions.CrystalReports
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared
Imports CrystalDecisions.Windows.Forms
Imports CrystalDecisions.ReportSource

Public Class frmFerramentasDANFEVisualizar
    Dim strAppPath As String = My.Application.Info.DirectoryPath.ToString
    Dim myDanfe As String = ""
    Dim PathBarra As String = strAppPath & "\temp\cod_barras.jpg", PathLogo As String = ""
    Dim strMargens As String, myMargens As CrystalDecisions.Shared.PageMargins
    Dim blnNoLogo As Boolean
    Dim strFldLogotipo As String = "logotipo1"
    Dim strFldxNome As String = "xNome1"
    Dim strFldxEndereco As String = "xEndereco1"

    Private Sub frmViewer_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try
            Me.WindowState = FormWindowState.Maximized
            Call LoadConfig()
        Catch ex As Exception
            Call SendError(ex.Message, ex.StackTrace)
        End Try
    End Sub
    ''' <summary>
    ''' Carrega as configurações básicas
    ''' </summary>
    ''' <remarks>3.4.3.26</remarks>
    Public Sub LoadConfig()
        Try
            Dim myNFe As New angNFeXMLGen
            With myNFe
                .Reset()
                .myConnString = strMyDBString
                .LoadConfigsFunctions()
            End With
            myNFe = Nothing
        Catch ex As Exception
            Throw New Exception("LoadConfig:Error:" & ex.Message)
        End Try
    End Sub
    ''' <summary>
    ''' Exibe o relatório do crytal
    ''' </summary>
    ''' <param name="XMLFilePath">Caminho completo do XML contendo o protocolo de autorização.</param>
    ''' <remarks>3.4.3.26</remarks>
    Private Sub ShowRel(ByVal XMLFilePath As String)
        Try
            Dim myCR As New ReportDocument
            Dim myDataset As New angDANFE
            '--
            myDataset.LoadConfig()
            myDataset.XMLFilePath = XMLFilePath
            '--
            With myCR
                .Load(myCrystalFilePath)
                .SetDataSource(myDataset.Dados)
                .PrintOptions.ApplyPageMargins(myDataset.Margens)
                If myDataset.NoLogo = True Then
                    Call UpdateReportObjectProperties(myCR, strFldLogotipo, 0, 0, 0, 0, False)
                    Call UpdateReportObjectProperties(myCR, strFldxNome, 0, 120, 0, 3480)
                    Call UpdateReportObjectProperties(myCR, strFldxEndereco, 0, 120, 0, 0)
                End If
            End With
            '--
            With CrystalReportViewer1
                .Visible = False
                '.ReportSource = rptXMLReport
                .ReportSource = myCR
                .Zoom(1) '-- 1=Page Width; 2=Entire Page
                .Visible = True
                '.Show()
                '.RefreshReport()
            End With
        Catch ex As Exception
            Call SendError(ex.Message, ex.StackTrace)
        End Try
    End Sub
    ''' <summary>
    ''' Atualiza propriedades do objeto dentro do crystal
    ''' </summary>
    ''' <param name="myReportDocument">Nome do documento do crystal</param>
    ''' <param name="reportObjectName">Nome do objet dentro do cystal</param>
    ''' <param name="top">Margem superior</param>
    ''' <param name="left">Margem esquerda</param>
    ''' <param name="height">Altura</param>
    ''' <param name="width">Largura</param>
    ''' <param name="Visible">Visiviel</param>
    ''' <remarks>3.4.3.25</remarks>
    Private Sub UpdateReportObjectProperties(ByVal myReportDocument As ReportDocument, _
                                             ByVal reportObjectName As String, _
                                             ByVal top As Integer, _
                                             ByVal left As Integer, _
                                             ByVal height As Integer, _
                                             ByVal width As Integer, _
                                             Optional ByVal Visible As Boolean = True)
        Try
            Dim myReportObject As ReportObject = myReportDocument.ReportDefinition.ReportObjects.Item(reportObjectName)
            If Not myReportObject Is Nothing Then
                With myReportObject
                    If top > 0 Then
                        .Top = top
                    End If
                    If left > 0 Then
                        .Left = left
                    End If
                    If height > 0 Then
                        .Height = height
                    End If
                    If width > 0 Then
                        .Width = width
                    End If
                    If Visible = False Then
                        .Height = 0
                        .Width = 0
                    End If
                End With

                'Dim myBorder As Border = myReportObject.Border()
                'myBorder.BackgroundColor = Color.White
                'myBorder.BorderColor = Color.Red

                'Dim myObjectFormat As ObjectFormat = myReportObject.ObjectFormat
                'myObjectFormat.EnableCanGrow = False
                'myObjectFormat.EnableSuppress = Supress
                'myObjectFormat.EnableCloseAtPageBreak = True
                'myObjectFormat.EnableKeepTogether = True
            End If
        Catch ex As Exception
            Throw New Exception(ex.Message)
        End Try
    End Sub

    Private Sub tbDanfeViewer_ItemClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.ToolStripItemClickedEventArgs) Handles tbDanfeViewer.ItemClicked
        Select Case e.ClickedItem.Tag
            Case "OPEN"
                Call AbrirProtocolo()
        End Select
    End Sub
    ''' <summary>
    ''' Abre o protocolo XML para ser impresso
    ''' </summary>
    Private Sub AbrirProtocolo()
        Try
            Dim AbrirComo As OpenFileDialog = New OpenFileDialog()
            Dim caminho As DialogResult

            With AbrirComo
                .Title = "Abrir como"
                .FileName = ""
                .Filter = "Protocolo de Autorização de Uso (*procNFe.xml)|*procNFe.xml|XML Desconhecido (*.xml)|*.xml"
                caminho = .ShowDialog
                If .FileName.ToString.Trim <> String.Empty Then
                    If IO.File.Exists(.FileName.ToString.Trim) Then
                        'Call CarregaXML(.FileName.ToString.Trim)
                        Call ShowRel(.FileName.ToString.Trim)
                    End If
                End If
            End With
        Catch ex As Exception
            Call MsgBox("OpenFile:Error:" & ex.Message)
        Finally

        End Try
    End Sub
    ''' <summary>
    ''' Envia comandos e requisições ao servidor RePro pelo TCP
    ''' </summary>
    Private Function CreateReturn(ByVal CodStatus As String, ByVal Mensagem As String) As String
        Dim myXml As New angXML
        Dim myOut As New XmlDocument
        Dim strOut As String = ""
        Try
            With myXml
                .Create()
                .Version = "1.0"
                .Encoding = "ISO-8859-1"
                .Add.Group("/ReproTCP")
                .Add.Tag("/ReproTCP/CodStatus", CodStatus)
                .Add.Tag("/ReproTCP/Mensagem", Mensagem)
                strOut = .XML
            End With
            With myOut
                .LoadXml(strOut)
                Return .OuterXml
            End With
        Catch ex As Exception
            With myXml
                .Create()
                .Version = "1.0"
                .Encoding = "ISO-8859-1"
                .Add.Group("/ReproTCP")
                .Add.Tag("/ReproTCP/CodStatus", "999")
                .Add.Tag("/ReproTCP/Mensagem", ex.Message)
                strOut = .XML
            End With
            With myOut
                .LoadXml(strOut)
                Return .OuterXml
            End With
        End Try
    End Function
    ''' <summary>
    ''' Decodifica strings Base64 - usado por emails
    ''' </summary>
    Private Sub Decode64()
        Try
            Dim strBase64 As String = "", strDecoded As String = ""
            Dim AbrirComo As OpenFileDialog = New OpenFileDialog()
            Dim caminho As DialogResult

            With AbrirComo
                .Title = "Abrir como"
                .FileName = ""
                .Filter = "Arquivos Texto simples (*.txt)|*.txt|todos os arquivos (*.*)|*.*"
                caminho = .ShowDialog
                If .FileName.ToString.Trim <> String.Empty Then
                    If IO.File.Exists(.FileName.ToString.Trim) Then
                        strBase64 = File.ReadAllText(.FileName.ToString.Trim)
                    End If
                End If
            End With

            strDecoded = System.Text.Encoding.ASCII.GetString(Convert.FromBase64String(strBase64))

            Debug.WriteLine(strDecoded)
        Catch ex As Exception
            Call SendError(ex.Message, ex.StackTrace)
        End Try
    End Sub
    ''' <summary>
    ''' Codifica strings para Base64 - usado por emails
    ''' </summary>
    Private Sub Encode64()
        Try
            Dim strBase64 As String = "", strDecoded As String = ""
            Dim AbrirComo As OpenFileDialog = New OpenFileDialog()
            Dim caminho As DialogResult

            With AbrirComo
                .Title = "Abrir como"
                .FileName = ""
                .Filter = "Arquivos Texto simples (*.txt)|*.txt|todos os arquivos (*.*)|*.*"
                caminho = .ShowDialog
                If .FileName.ToString.Trim <> String.Empty Then
                    If IO.File.Exists(.FileName.ToString.Trim) Then
                        strBase64 = File.ReadAllText(.FileName.ToString.Trim)
                    End If
                End If
            End With

            strDecoded = Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(strBase64))

            Debug.WriteLine(strDecoded)
        Catch ex As Exception
            Call SendError(ex.Message, ex.StackTrace)
        End Try
    End Sub
End Class
